package com.ruoyi.chat.userController;

import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.info.domain.FhInfoUser;
import com.ruoyi.info.domain.FhInfoUsertask;
import com.ruoyi.info.service.IFhInfoUserService;
import com.ruoyi.info.service.IFhInfoUsertaskService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.test.aop.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 好友Controller
 * 
 * @author ruoyi
 * @date 2024-11-11
 */
@Api(tags = "聊天好友接口")
@RestController
@RequestMapping("/chat/userFriend")
public class UserFhChatFriendController extends BaseController
{
    @Autowired
    private IFhChatFriendService fhChatFriendService;

    @Autowired
    private IFhInfoUserService iFhInfoUserService;

    @Autowired
    private IFhInfoUsertaskService iFhInfoUsertaskService;



    /**
     * 获取推荐朋友列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("获取推荐朋友列表")
    @GetMapping("/referFriendList")
    public R<List<FhChatFriend>> referFriendList()
    {
        try {
            Long userId = UserThreadLocal.getUser();
            //如果有用户关注了我，我没关注别人，则为推荐朋友
            FhChatFriend fhChatFriend = new FhChatFriend();
            //粉丝列表（关注我的用户）
            fhChatFriend.setFriendId(userId);
            List<FhChatFriend> fansList = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            //好友列表（我关注的用户）
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> friendList = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            //推荐好友列表
            List<FhChatFriend> referFriendList = new ArrayList<>();
            for (int i = 0; i < fansList.size(); i++) {
                //粉丝id
                Long fansUserId = fansList.get(i).getUserId();
                boolean flag = true;
                for (int j = 0; j < friendList.size(); j++) {
                    if(friendList.get(j).getFriendId()==fansUserId){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    referFriendList.add(fansList.get(i));
                }
            }
            return R.ok(referFriendList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 搜索好友
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("搜索好友")
    @GetMapping("/selectFriendByName")
    public R<List<FhInfoUser>> selectFrient(String name)
    {
        try{
            List<FhInfoUser> fhInfoUsersVo = new ArrayList<>();

            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setName(name);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            //去除掉已关注的好友
            List<FhChatFriend> fhChatFriendList = fhChatFriendService.selectFhChatFriendByUserId(userId);
            for (int i = 0; i < fhInfoUsers.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < fhChatFriendList.size(); j++) {
                    if(Objects.equals(fhInfoUsers.get(i).getUserId(), fhChatFriendList.get(j).getFriendId())){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    fhInfoUsersVo.add(fhInfoUsers.get(i));
                }
            }

            return R.ok(fhInfoUsersVo);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 根据通讯录获取朋友列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("根据通讯录获取朋友列表")
    @GetMapping("/friendListByPhoneList")
    public  R<List<FhInfoUser>> friendListByPhoneList(String phoneList)
    {
        try {
            List<FhInfoUser> fhInfoUsersVo = new ArrayList<>();

            Long userId = UserThreadLocal.getUser();
            String[] phoneListValue = phoneList.split(",");
            FhInfoUser fhInfoUser = new FhInfoUser();
            //根据通讯录获取朋友列表
            List<FhInfoUser> friendListByPhoneList = new ArrayList<>();
            for (int i = 0; i < phoneListValue.length; i++) {
                fhInfoUser.setPhone(phoneListValue[i]);
                List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
                if(!fhInfoUsers.isEmpty()){
                    friendListByPhoneList.add(fhInfoUsers.get(0));
                }
            }
            //去除掉已关注的好友
            List<FhChatFriend> fhChatFriendList = fhChatFriendService.selectFhChatFriendByUserId(userId);
            for (int i = 0; i < friendListByPhoneList.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < fhChatFriendList.size(); j++) {
                    if(Objects.equals(friendListByPhoneList.get(i).getUserId(), fhChatFriendList.get(j).getFriendId())){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    fhInfoUsersVo.add(friendListByPhoneList.get(i));
                }
            }

            return R.ok(fhInfoUsersVo);
        }catch (Exception e){
            return R.fail();
        }

    }


    /**
     * 关注好友
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("关注好友")
    @Log(title = "好友", businessType = BusinessType.INSERT)
    @PostMapping
    public R<String> add(Long friendId)
    {
        try {
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUser = new FhInfoUser();
            //修改用户信息的关注数
            fhInfoUser.setUserId(userId);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long followers = fhInfoUsers.get(0).getFollowers();
            followers+=1;
            fhInfoUsers.get(0).setFollowers(followers);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers.get(0));
            //修改用户信息的粉丝数
            fhInfoUser.setUserId(friendId);
            List<FhInfoUser> fhInfoUsers1 = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long fans = fhInfoUsers1.get(0).getFans();
            fans+=1;
            fhInfoUsers1.get(0).setFans(fans);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers1.get(0));
            //关注该用户
            FhInfoUser fhInfoUserFriend = iFhInfoUserService.selectFhInfoUserByUserId(friendId);
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendAdress(fhInfoUserFriend.getAddress());
            fhChatFriend.setFriendImage(fhInfoUserFriend.getImage());
            fhChatFriend.setFriendName(fhInfoUserFriend.getName());
            fhChatFriend.setFriendId(friendId);
            fhChatFriend.setCrateTime(new Date());
            fhChatFriend.setFriendPhone(fhInfoUserFriend.getPhone());

            fhChatFriendService.insertFhChatFriend(fhChatFriend);

            //修改添加好友任务完成状态
            compleTask(2L);

            return R.ok("关注成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 用户完成任务加积分
     */
    public R<String> compleTask(Long taskId)
    {
        try {
            //修改信息表
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUserInfo = iFhInfoUserService.selectFhInfoUserByUserId(userId);
            Long points = fhInfoUserInfo.getPoints();
            points+=10;
            fhInfoUserInfo.setPoints(points);
            iFhInfoUserService.updateFhInfoUser(fhInfoUserInfo);
            //修改任务表状态，1为未完成，0为完成
            FhInfoUsertask fhInfoUsertask = new FhInfoUsertask();
            fhInfoUsertask.setUserId(userId);
            fhInfoUsertask.setTaskId(taskId);
            fhInfoUsertask.setCompletionStatus("0");
            iFhInfoUsertaskService.updateFhInfoUsertaskByUserIdAndTaskId(fhInfoUsertask);
            return R.ok("完成成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }


    /**
     * 取消关注好友
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("取消关注好友")
    @Log(title = "好友", businessType = BusinessType.DELETE)
    @DeleteMapping()
    public R<String> remove(Long friendId)
    {
        try {
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUser = new FhInfoUser();
            //修改用户信息的关注数
            fhInfoUser.setUserId(userId);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long followers = fhInfoUsers.get(0).getFollowers();
            followers-=1;
            fhInfoUsers.get(0).setFollowers(followers);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers.get(0));
            //修改用户信息的粉丝数
            fhInfoUser.setUserId(friendId);
            List<FhInfoUser> fhInfoUsers1 = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long fans = fhInfoUsers1.get(0).getFans();
            fans-=1;
            fhInfoUsers1.get(0).setFans(fans);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers1.get(0));
            //取消关注该用户
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            fhChatFriendService.deleteFhChatFriendById(fhChatFriends.get(0).getId());

            return R.ok("取消关注成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询好友列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("查询好友列表")
    @GetMapping("/list")
    public R<List<FhChatFriend>> list()
    {
        try {
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(UserThreadLocal.getUser());
            List<FhChatFriend> list = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            return R.ok(list);
        }catch (Exception e){
            return R.fail();
        }
    }


    /**
     * 获取好友详细信息
     */
    @Anonymous
    @UserLoginToken
//    @ApiOperation("获取好友详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(fhChatFriendService.selectFhChatFriendById(id));
    }





}
